//
//  LoginDataMng.m
//  habit
//
//  Created by huck on 15-9-2.
//  Copyright (c) 2015年 custom. All rights reserved.
//

#import "LoginDataMng.h"
#import "AppUtils.h"
#import "Config.h"
#import "HttpRequest.h"
//#import <ALBBPush/CloudPushSDK.h>
#import "StoreManager.h"
#import "Base64.h"
#import "ServerMng.h"


@implementation LoginDataItem


- (void)setInfo:(NSDictionary *)dict
{
    _userName = [AppUtils toString:dict[@"loginName"]];
    _userId = [AppUtils toString:dict[@"id"]];
    _name = [AppUtils toString:dict[@"name"]];
    
    NSArray *list = dict[@"roleList"];
    NSMutableArray *roles = [NSMutableArray array];
    for(NSDictionary *dic in list) {
        RoleInfoData *data = [[RoleInfoData alloc] init];
        [data setInfo:dic];
        [roles addObject:data];
    }
    _roleList = roles;
    
    _mobile = [AppUtils toString:dict[@"mobile"]];
    _phone = [AppUtils toString:dict[@"phone"]];
    _email = [AppUtils toString:dict[@"email"]];
    _beregion = [AppUtils toString:dict[@"beregion"]];
    _beregionCode = [AppUtils toString:dict[@"beregionCode"]];
}

-(BOOL)canSuperView
{
    NSArray *arr= @[ROLE_TYPE_DDY,ROLE_TYPE_WSB,ROLE_TYPE_ADMIN];
    for(RoleInfoData *data in _roleList){
        if([arr containsObject:data.roleCode] ){
            return YES;
        }
    }
    return NO;
}

@end

@implementation RoleInfoData

- (void)setInfo:(NSDictionary *)dic
{
    _roleCode = [AppUtils toString:dic[@"roleCode"]];
    _roleName = [AppUtils toString:dic[@"roleName"]];
}

@end

@interface LoginDataMng()

@end
@implementation LoginDataMng

+ (instancetype)sharedInstance
{
    static LoginDataMng *instance;
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        instance = [[LoginDataMng alloc] init];
    });
    return instance;
}

- (void)clearUserInfo
{
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    只清密码不清用户名
    LoginDataItem *item = [self getLoginUser];
    [self saveLoginUser:item.userName password:nil];
//    [userDefaults removeObjectForKey:LOGIN_USER_ITEM];
//    [userDefaults synchronize];
}

- (LoginDataItem *)getLoginUser:(NSDictionary *)result
{
    LoginDataItem *item = [[LoginDataItem alloc] init];
    if(result != nil){
        
        [item setInfo:result];
//        item.userName = result[@"userName"];
        item.password = result[@"password"];
    }
    return item;
}

- (LoginDataItem *)getLoginUser
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *result = [userDefaults objectForKey:LOGIN_USER_ITEM];
    return [self getLoginUser:result];
}

- (void)saveLoginUser:(NSMutableDictionary *)result
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setValue:result forKey:LOGIN_USER_ITEM];
    [userDefaults synchronize];
}


- (void)saveLoginUser:(NSString *)username password:(NSString *)pwd
{
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    [result setValue:username forKey:@"loginName"];
    [result setValue:pwd forKey:@"password"];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setValue:result forKey:LOGIN_USER_ITEM];
    [userDefaults synchronize];
}

- (NSString *)getPushDeviceId
{
    return  @"测试下";//[CloudPushSDK getDeviceId];
}

- (void)login:(NSString *)username password:(NSString *)password isReload:(BOOL)isReload complete:(void (^)(BOOL success))complete
{
    if (([AppUtils isEmpty:username] || [AppUtils isEmpty:password]) ) {
        if(!isReload) {
            [AppUtils showErrorAlert:@"用户名或密码不能为空"];
        }
        complete(NO);
        return;
    }
    NSString *url = @"/app_login";
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setValue:[[NSString stringWithFormat:@"%@%@",BASE64_PREFIX_STR,username] base64EncodedString] forKey:@"userName"];
    [params setValue:[[NSString stringWithFormat:@"%@%@",BASE64_PREFIX_STR,password] base64EncodedString] forKey:@"password"];
    [params setValue:[self getPushDeviceId] forKey:@"deviceId"];

    [[HttpRequest sharedHttpRequest] get:url params:params complete:^(BOOL success, NSDictionary *result) {
        if (success) {
            NSDictionary *dict = result[@"data"];
            LOGIN_USER.password = password;
            [LOGIN_USER setInfo:dict];
            
            NSMutableDictionary *saveDict = [NSMutableDictionary dictionaryWithDictionary:dict];
            [saveDict setValue:password forKey:@"password"];
            [self saveLoginUser:saveDict];
            
            [AppUtils postNotificationName:XGLoginSuccessNotification];
            complete(YES);
        }else{
            complete(NO);
            if(!isReload) {
                [AppUtils showErrorAlert: result[@"message"]];
            }
        }
    }];
}

- (void)onUserLogin
{
    [self bindPushInfo];
}

- (void)bindPushInfo
{
//    NSString *bindUserId  = [Config getValue:ConfigBindPushUserId];
//    
//    [self unBindPushInfo:LOGIN_USER.userId callback:^{
//        // 收款通知已开启==配置中开启通知
//        if (LOGIN_USER.isPushOpen) {
//            
//            [CloudPushSDK bindAccount:LOGIN_USER.userId withCallback:^(BOOL status) {
//                if (status) {
//                    NSLog(@"==================> 云推送=绑定=账号%@成功,deviceID=%@",LOGIN_USER.userId,[CloudPushSDK getDeviceId]);
//                    if([ServerMng sharedServerMng].showSavearray){
//                        [[ServerMng sharedServerMng].saveArray addObject:[NSString stringWithFormat:@"==================> 云推送=绑定=账号%@成功,deviceID=%@",LOGIN_USER.userId,[CloudPushSDK getDeviceId]]];
//                    }
//
//                    if([AppUtils isEmpty:bindUserId] ){
//                        [Config setValue:ConfigBindPushUserId value:LOGIN_USER.userId];
//                    }else{
//                        if(![LOGIN_USER.userId isEqualToString:bindUserId]){
//                            [self unBindPushInfo:bindUserId callback:^{
//                            }];
//                            [Config setValue:ConfigBindPushUserId value:LOGIN_USER.userId];
//                        }
//                    }
//                }
//                
//            }];
//        }
//    }];
}

- (void)unBindPushInfo:(NSString*)account callback:(void(^)())success
{
//    [CloudPushSDK unbindAccount:account withCallback:^(BOOL status) {
//        if (status) {
//            NSLog(@"==================> 云推送解绑账号%@成功",account);
//            if([ServerMng sharedServerMng].showSavearray){
//                [[ServerMng sharedServerMng].saveArray addObject:[NSString stringWithFormat:@"==================> 云推送解绑账号成功"]];
//            }
//
//            //            [Toast makeText:@"解绑成功"];
//        } else {
//            NSLog(@"==================> 云推送解绑账号%@失败",account);
//            //               [Toast makeText:@"解绑失败"];
//        }
//        success();
//    }];
}

/**
 * 暗地里重新登录
 */
- (void)reLogin:(void (^)(BOOL success))complete
{
    [self login:LOGIN_USER.userName password:LOGIN_USER.password isReload:YES  complete:^(BOOL success) {
        if(success){
            complete(YES);
        }else{
            [self loginOutWithoutRequest];
        }
    }];
}

-(void)loginOut
{
//    [[LoginDataMng sharedInstance] unBindPushInfo:LOGIN_USER.userId callback:^{
        //    告知服务端退出
        NSString *urlName = @"cod.user.loginout";
        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        [params setValue:LOGIN_USER.userName forKey:@"login_id"];
//        [[HttpRequest sharedHttpRequest] get:urlName params:params complete:^(BOOL success, NSDictionary *result) {
            [[LoginDataMng sharedInstance] clearUserInfo];
            [ServerMng sharedServerMng].loginUser = [[LoginDataMng sharedInstance] getLoginUser];
//            [[ServerMng sharedServerMng] initLoginWindow:YES];
    [AppUtils postNotificationName:XGLoginOutSuccessNotification];
//        }];
//    }];
}
-(void)loginOutWithoutRequest
{
//    [[LoginDataMng sharedInstance] unBindPushInfo:LOGIN_USER.userId callback:^{
        [[LoginDataMng sharedInstance] clearUserInfo];
        [ServerMng sharedServerMng].loginUser = [[LoginDataMng sharedInstance] getLoginUser];
//        [[ServerMng sharedServerMng] initLoginWindow:YES];
//    }];
}



@end
